<?php
/**
* Numedia Studio Framework
* 
* Translation library.
*
* This is called by the theme "init_admin.php"
*/

// HOOKS
add_filter('the_content',	'ns_translate_content', 0);
add_filter('the_title',		'ns_translate_content', 0);
add_filter('wp_title',		'ns_translate_content', 0);
//add_filter('locale',		'ns_localeForCurrentLanguage',99);
//add_filter('get_the_time',	'qtrans_timeFromPostForCurrentLanguage',0,3);
//add_filter('get_the_date',	'qtrans_dateFromPostForCurrentLanguage',0,4);

// TRANSLATION

// enable the use of following languages (order=>language)
$ns_config['enabled_languages'] = array(
	'0' => 'en_US',
	'1' => 'fr_FR', 
	'2' => 'ar_MA', 
	'3' => 'tz_MA'
);

// sets default language
$ns_config['default_language'] = 'en_US';

// enables browser language detection
$ns_config['detect_browser_language'] = true;

// hide pages without content
$ns_config['hide_untranslated'] = false;

// automatically update .mo files
$ns_config['auto_update_mo'] = true;

// hide language tag for default language
$ns_config['hide_default_language'] = true;

// Names for languages in the corresponding language, add more if needed
$ns_config['language_name']['en_US'] = "English";
$ns_config['language_name']['fr_FR'] = "Français";
$ns_config['language_name']['ar_MA'] = "العربية";
$ns_config['language_name']['tz_MA'] = "ⵜⴰⵎⴰⵣⵉⵖⵜ";
$ns_config['language_name']['de'] = "Deutsch";
$ns_config['language_name']['zh'] = "中文";
$ns_config['language_name']['fi'] = "suomi";
$ns_config['language_name']['nl'] = "Nederlands";
$ns_config['language_name']['sv'] = "Svenska";
$ns_config['language_name']['it'] = "Italiano";
$ns_config['language_name']['ro'] = "Română";
$ns_config['language_name']['hu'] = "Magyar";
$ns_config['language_name']['ja'] = "日本語";
$ns_config['language_name']['es'] = "Español";
$ns_config['language_name']['vi'] = "Tiếng Việt";
$ns_config['language_name']['pt'] = "Português";

// Locales for languages
// see locale -a for available locales
$ns_config['locale']['en'] = "en_US";
$ns_config['locale']['fr'] = "fr_FR";
$ns_config['locale']['ar'] = "ar_AR";
$ns_config['locale']['tz'] = "tz_MA";
$ns_config['locale']['fi'] = "fi";
$ns_config['locale']['nl'] = "nl_NL";
$ns_config['locale']['se'] = "sv_SE";
$ns_config['locale']['it'] = "it_IT";
$ns_config['locale']['ro'] = "ro_RO";
$ns_config['locale']['hu'] = "hu_HU";
$ns_config['locale']['ja'] = "ja";
$ns_config['locale']['es'] = "es_ES";
$ns_config['locale']['vi'] = "vi";
$ns_config['locale']['ar'] = "ar";
$ns_config['locale']['pt'] = "pt_BR";

// Language not available messages
// %LANG:<normal_seperator>:<last_seperator>% generates a list of languages sepe
$ns_config['not_available']['en_US'] = "Sorry, this entry is only available in %LANG:, : and %.";
$ns_config['not_available']['fr_FR'] = "Désolé, cet article est seulement disponible en %LANG:, : et %.";
$ns_config['not_available']['ar_MA'] = "عفوا، هذه المدخلة موجودة فقط في %LANG:, : و %.";
$ns_config['not_available']['tz_MA'] = "Ssurfakh, cet article est seulement disponible en %LANG:, : et %.";
$ns_config['not_available']['de'] = "Leider ist der Eintrag nur auf %LANG:, : und % verfügbar.";
$ns_config['not_available']['zh'] = "对不起，此内容只适用于%LANG:，:和%。";
$ns_config['not_available']['fi'] = "Anteeksi, mutta tämä kirjoitus on saatavana ainoastaan näillä kielillä: %LANG:, : ja %.";
$ns_config['not_available']['nl'] = "Onze verontschuldigingen, dit bericht is alleen beschikbaar in %LANG:, : en %.";
$ns_config['not_available']['sv'] = "Tyvärr är denna artikel enbart tillgänglig på %LANG:, : och %.";
$ns_config['not_available']['it'] = "Ci spiace, ma questo articolo è disponibile soltanto in %LANG:, : e %.";
$ns_config['not_available']['ro'] = "Din păcate acest articol este disponibil doar în %LANG:, : și %.";
$ns_config['not_available']['hu'] = "Sajnos ennek a bejegyzésnek csak %LANG:, : és % nyelvű változata van.";
$ns_config['not_available']['ja'] = "申し訳ありません、このコンテンツはただ今　%LANG:、 :と %　のみです。";
$ns_config['not_available']['es'] = "Disculpa, pero esta entrada está disponible sólo en %LANG:, : y %.";
$ns_config['not_available']['vi'] = "Rất tiếc, mục này chỉ tồn tại ở %LANG:, : và %.";
$ns_config['not_available']['pt'] = "Desculpe-nos, mas este texto esta apenas disponível em %LANG:, : y %.";

// strftime usage (backward compability)
$ns_config['use_strftime'] = QT_DATE;

// Date Configuration
$ns_config['date_format']['en'] = '%A %B %e%q, %Y';
$ns_config['date_format']['de'] = '%A, der %e. %B %Y';
$ns_config['date_format']['zh'] = '%x %A';
$ns_config['date_format']['fi'] = '%e.&m.%C';
$ns_config['date_format']['fr'] = '%A %e %B %Y';
$ns_config['date_format']['nl'] = '%d/%m/%y';
$ns_config['date_format']['sv'] = '%Y/%m/%d';
$ns_config['date_format']['it'] = '%e %B %Y';
$ns_config['date_format']['ro'] = '%A, %e %B %Y';
$ns_config['date_format']['hu'] = '%Y %B %e, %A';
$ns_config['date_format']['ja'] = '%Y年%m月%d日';
$ns_config['date_format']['es'] = '%d de %B de %Y';
$ns_config['date_format']['vi'] = '%d/%m/%Y';
$ns_config['date_format']['ar'] = '%d/%m/%Y';
$ns_config['date_format']['pt'] = '%d de %B de %Y';

$ns_config['time_format']['en'] = '%I:%M %p';
$ns_config['time_format']['de'] = '%H:%M';
$ns_config['time_format']['zh'] = '%I:%M%p';
$ns_config['time_format']['fi'] = '%H:%M';
$ns_config['time_format']['fr'] = '%H:%M';
$ns_config['time_format']['nl'] = '%H:%M';
$ns_config['time_format']['sv'] = '%H:%M';
$ns_config['time_format']['it'] = '%H:%M';
$ns_config['time_format']['ro'] = '%H:%M';
$ns_config['time_format']['hu'] = '%H:%M';
$ns_config['time_format']['ja'] = '%H:%M';
$ns_config['time_format']['es'] = '%H:%M hrs.';
$ns_config['time_format']['vi'] = '%H:%M';
$ns_config['time_format']['ar'] = '%H:%M';
$ns_config['time_format']['pt'] = '%H:%M hrs.';

function ns_qtrans_join($texts) {
	global $ns_config;
	if(!is_array($texts)) $texts = ns_qtrans_split($texts, false);
	$split_regex = "#<!--more-->#ism";
	$max = 0;
	$text = "";
	
	foreach($ns_config['enabled_languages'] as $language) {
		$texts[$language] = preg_split($split_regex, $texts[$language]);
		if(sizeof($texts[$language]) > $max) $max = sizeof($texts[$language]);
	}
	for($i=0;$i<$max;$i++) {
		if($i>=1) {
			$text .= '<!--more-->';
		}
		foreach($ns_config['enabled_languages'] as $language) {
			if(isset($texts[$language][$i]) && $texts[$language][$i] !== '') {
				$text .= '<!--:'.$language.'-->'.$texts[$language][$i].'<!--:-->';
			}
		}
	}
	return $text;
}

// splits text with language tags into array
function ns_qtrans_split($text, $quicktags = true) {
	global $ns_config;
	
	//init vars
	$split_regex = "#(<!--[^-]*-->|\[:[a-z_]{5}\])#ism";
	$current_language = "";
	$result = array();
	foreach($ns_config['enabled_languages'] as $language) {
		$result[$language] = "";
	}
	
	// split text at all xml comments
	$blocks = preg_split($split_regex, $text, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
	foreach($blocks as $block) {
		# detect language tags
		if(preg_match("#^<!--:([a-z_]{5})-->$#ism", $block, $matches)) {
			if(ns_qtrans_isEnabled($matches[1])) {
				$current_language = $matches[1];
			} else {
				$current_language = "invalid";
			}
			continue;
		// detect quicktags
		} elseif($quicktags && preg_match("#^\[:([a-z_]{5})\]$#ism", $block, $matches)) {
			if(ns_qtrans_isEnabled($matches[1])) {
				$current_language = $matches[1];
			} else {
				$current_language = "invalid";
			}
			continue;
		// detect ending tags
		} elseif(preg_match("#^<!--:-->$#ism", $block, $matches)) {
			$current_language = "";
			continue;
		// detect defective more tag
		} elseif(preg_match("#^<!--more-->$#ism", $block, $matches)) {
			foreach($ns_config['enabled_languages'] as $language) {
				$result[$language] .= $block;
			}
			continue;
		}
		// correctly categorize text block
		if($current_language == "") {
			// general block, add to all languages
			foreach($ns_config['enabled_languages'] as $language) {
				$result[$language] .= $block;
			}
		} elseif($current_language != "invalid") {
			// specific block, only add to active language
			$result[$current_language] .= $block;
		}
	}
	foreach($result as $lang => $lang_content) {
		$result[$lang] = preg_replace("#(<!--more-->|<!--nextpage-->)+$#ism","",$lang_content);
	}
	return $result;
}

function ns_qtrans_isEnabled($lang) {
	global $ns_config;
	return in_array($lang, $ns_config['enabled_languages']);
}

function ns_translate_content($content) {
	global $ns_config;
	return ns_qtrans_use(get_locale(), $content, false);
}

function ns_qtrans_use($lang, $text, $show_available = false) {
	global $ns_config;
	// return full string if language is not enabled
	if(!ns_qtrans_isEnabled($lang)) return $text;
	if(is_array($text)) {
		// handle arrays recursively
		foreach($text as $key => $t) {
			$text[$key] = ns_qtrans_use($lang,$text[$key],$show_available);
		}
		return $text;
	}
	
	if(is_object($text)||@get_class($text) == '__PHP_Incomplete_Class') {
		foreach(get_object_vars($text) as $key => $t) {
			$text->$key = ns_qtrans_use($lang,$text->$key,$show_available);
		}
		return $text;
	}
	
	// prevent filtering weird data types and save some resources
	if(!is_string($text) || $text == '') {
		return $text;
	}
	
	// get content
	$content = ns_qtrans_split($text);
	// find available languages
	$available_languages = array();
	foreach($content as $language => $lang_text) {
		$lang_text = trim($lang_text);
		if(!empty($lang_text)) $available_languages[] = $language;
	}
	
	// if no languages available show full text
	if(sizeof($available_languages)==0) return $text;
	// if content is available show the content in the requested language

	//return var_dump( $content[$lang] );
	if(!empty($content[$lang])) {
		return $content[$lang];
	}
	// content not available in requested language (bad!!) what now?
	if(!$show_available){
		// check if content is available in default language, if not return first language found. (prevent empty result)
		if($lang!=$ns_config['default_language'])
			//return "(".$ns_config['language_name'][$ns_config['default_language']].") ".ns_qtrans_use($ns_config['default_language'], $text, $show_available);
			return ns_qtrans_use($ns_config['default_language'], $text, $show_available);
		foreach($content as $language => $lang_text) {
			$lang_text = trim($lang_text);
			if(!empty($lang_text)) {
				//return "(".$ns_config['language_name'][$language].") ".$lang_text;
				return $lang_text;
			}
		}
	}
	// display selection for available languages
	$available_languages = array_unique($available_languages);
	$language_list = "";
	if(preg_match('/%LANG:([^:]*):([^%]*)%/',$ns_config['not_available'][$lang],$match)) {
		$normal_seperator = $match[1];
		$end_seperator = $match[2];
		// build available languages string backward
		$i = 0;
		foreach($available_languages as $language) {
			if($i==1) $language_list  = $end_seperator.$language_list;
			if($i>1) $language_list  = $normal_seperator.$language_list;
			//$language_list = "<a href=\"".ns_qtrans_convertURL('', $language)."\">".$ns_config['language_name'][$language]."</a>".$language_list;
			$language_list = "<a href=\"#\">".$ns_config['language_name'][$language]."</a>".$language_list;
			$i++;
		}
	}
	return "<p>".preg_replace('/%LANG:([^:]*):([^%]*)%/', $language_list, $ns_config['not_available'][$lang])."</p>";
}


function ns_localeForCurrentLanguage($locale){
	global $ns_config;
	// try to figure out the correct locale
	$locale = array();
	$locale[] = $ns_config['locale'][$ns_config['language']].".utf8";
	$locale[] = $ns_config['locale'][$ns_config['language']]."@euro";
	$locale[] = $ns_config['locale'][$ns_config['language']];
	$locale[] = $ns_config['windows_locale'][$ns_config['language']];
	$locale[] = $ns_config['language'];
	
	// return the correct locale and most importantly set it (wordpress doesn't, which is bad)
	// only set LC_TIME as everyhing else doesn't seem to work with windows
	setlocale(LC_TIME, $locale);
	
	return $ns_config['locale'][$ns_config['language']];
}

function qtrans_timeFromPostForCurrentLanguage($old_date, $format = '', $post = null, $gmt = false) {
	$post = get_post($post);
	
	$post_date = $gmt? $post->post_date_gmt : $post->post_date;
	return qtrans_strftime(qtrans_convertTimeFormat($format), mysql2date('U',$post_date), $old_date);
}

/* BEGIN DATE TIME FUNCTIONS */

function qtrans_strftime($format, $date, $default = '', $before = '', $after = '') {
	// don't do anything if format is not given
	if($format=='') return $default;
	// add date suffix ability (%q) to strftime
	$day = intval(ltrim(strftime("%d",$date),'0'));
	$search = array();
	$replace = array();
	
	// date S
	$search[] = '/(([^%])%q|^%q)/';
	if($day==1||$day==21||$day==31) { 
		$replace[] = '$2st';
	} elseif($day==2||$day==22) {
		$replace[] = '$2nd';
	} elseif($day==3||$day==23) {
		$replace[] = '$2rd';
	} else {
		$replace[] = '$2th';
	}
	
	$search[] = '/(([^%])%E|^%E)/'; $replace[] = '${2}'.$day; // date j
	$search[] = '/(([^%])%f|^%f)/'; $replace[] = '${2}'.date('w',$date); // date w
	$search[] = '/(([^%])%F|^%F)/'; $replace[] = '${2}'.date('z',$date); // date z
	$search[] = '/(([^%])%i|^%i)/'; $replace[] = '${2}'.date('n',$date); // date i
	$search[] = '/(([^%])%J|^%J)/'; $replace[] = '${2}'.date('t',$date); // date t
	$search[] = '/(([^%])%k|^%k)/'; $replace[] = '${2}'.date('L',$date); // date L
	$search[] = '/(([^%])%K|^%K)/'; $replace[] = '${2}'.date('B',$date); // date B
	$search[] = '/(([^%])%l|^%l)/'; $replace[] = '${2}'.date('g',$date); // date g
	$search[] = '/(([^%])%L|^%L)/'; $replace[] = '${2}'.date('G',$date); // date G
	$search[] = '/(([^%])%N|^%N)/'; $replace[] = '${2}'.date('u',$date); // date u
	$search[] = '/(([^%])%Q|^%Q)/'; $replace[] = '${2}'.date('e',$date); // date e
	$search[] = '/(([^%])%o|^%o)/'; $replace[] = '${2}'.date('I',$date); // date I
	$search[] = '/(([^%])%O|^%O)/'; $replace[] = '${2}'.date('O',$date); // date O
	$search[] = '/(([^%])%s|^%s)/'; $replace[] = '${2}'.date('P',$date); // date P
	$search[] = '/(([^%])%v|^%v)/'; $replace[] = '${2}'.date('T',$date); // date T
	$search[] = '/(([^%])%1|^%1)/'; $replace[] = '${2}'.date('Z',$date); // date Z
	$search[] = '/(([^%])%2|^%2)/'; $replace[] = '${2}'.date('c',$date); // date c
	$search[] = '/(([^%])%3|^%3)/'; $replace[] = '${2}'.date('r',$date); // date r
	$search[] = '/(([^%])%4|^%4)/'; $replace[] = '${2}'.$date; // date U
	$format = preg_replace($search,$replace,$format);
	return $before.strftime($format, $date).$after;
}

function qtrans_convertTimeFormat($format) {
	global $ns_config;
	if(isset($ns_config['time_format'][$ns_config['language']])) {
		$default_format = $ns_config['time_format'][$ns_config['language']];
	} elseif(isset($ns_config['time_format'][$ns_config['default_language']])) {
		$default_format = $ns_config['time_format'][$ns_config['default_language']];
	} else {
		$default_format = '';
	}
	return qtrans_convertFormat($format, $default_format);
}

function qtrans_convertFormat($format, $default_format) {
	global $ns_config;
	// check for multilang formats
	$format = ns_qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($format);
	$default_format = ns_qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($default_format);
	switch($ns_config['use_strftime']) {
		case QT_DATE:
			if($format=='') $format = $default_format;
			return qtrans_convertDateFormatToStrftimeFormat($format);
		case QT_DATE_OVERRIDE:
			return qtrans_convertDateFormatToStrftimeFormat($default_format);
		case QT_STRFTIME:
			return $format;
		case QT_STRFTIME_OVERRIDE:
			return $default_format;
	}
}

function ns_qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($content) {
	global $ns_config;
	return ns_qtrans_use($ns_config['language'], $content, false);
}

function qtrans_convertDateFormatToStrftimeFormat($format) {
	$mappings = array(
		'd' => '%d',
		'D' => '%a',
		'j' => '%E',
		'l' => '%A',
		'N' => '%u',
		'S' => '%q',
		'w' => '%f',
		'z' => '%F',
		'W' => '%V',
		'F' => '%B',
		'm' => '%m',
		'M' => '%b',
		'n' => '%i',
		't' => '%J',
		'L' => '%k',
		'o' => '%G',
		'Y' => '%Y',
		'y' => '%y',
		'a' => '%P',
		'A' => '%p',
		'B' => '%K',
		'g' => '%l',
		'G' => '%L',
		'h' => '%I',
		'H' => '%H',
		'i' => '%M',
		's' => '%S',
		'u' => '%N',
		'e' => '%Q',
		'I' => '%o',
		'O' => '%O',
		'P' => '%s',
		'T' => '%v',
		'Z' => '%1',
		'c' => '%2',
		'r' => '%3',
		'U' => '%4'
	);
	
	$date_parameters = array();
	$strftime_parameters = array();
	$date_parameters[] = '#%#'; 			$strftime_parameters[] = '%%';
	foreach($mappings as $df => $sf) {
		$date_parameters[] = '#(([^%\\\\])'.$df.'|^'.$df.')#';	$strftime_parameters[] = '${2}'.$sf;
	}
	// convert everything
	$format = preg_replace($date_parameters, $strftime_parameters, $format);
	// remove single backslashes from dates
	$format = preg_replace('#\\\\([^\\\\]{1})#','${1}',$format);
	// remove double backslashes from dates
	$format = preg_replace('#\\\\\\\\#','\\\\',$format);
	return $format;
}